package org.tity.commons.math;

import java.util.Stack;

 
/**
 * 数位进制转换工具
 * @author fangjieli 
 * */
public class NumberSystem {
	
	private NumberSystem() {};

	private static char[] array = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
	private static String numStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	/**
	 *  10进制转为其他进制，除留取余，逆序排列
	 *  @param number 十进制数字
	 *  @param n	进制
	 *  @return  n进制值
	 */
	public static String toN(long number, int n) {
		Long rest = number;
		Stack<Character> stack = new Stack<>();
		StringBuilder result = new StringBuilder(0);
		while (rest != 0) {
			stack.add(array[new Long((rest % n)).intValue()]);
			rest = rest / n;
		}
		for (; !stack.isEmpty();) {
			result.append(stack.pop());
		}
		return result.length() == 0 ? "0" : result.toString();
	}

	private static final int TEN=10;
	
	/**
	 * 其他进制转为10进制，按权展开
	 * @param number n进制值
	 * @param n	进制
	 * @return	十进制值
	 */
	public static long to10(String number, int n) {
		char ch[] = number.toCharArray();
		int len = ch.length;
		long result = 0;
		if (n == TEN) {
			return Long.parseLong(number);
		}
		long base = 1;
		for (int i = len - 1; i >= 0; i--) {
			int index = numStr.indexOf(ch[i]);
			result += index * base;
			base *= n;
		}
		return result;
	}
 
}
